package utils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URISyntaxException;

import com.google.gson.Gson;

public class JSONUtils {

	private static Gson singletonGson;

	private synchronized static Gson getSingletonGson() {
		if (singletonGson == null) {
			singletonGson = new Gson();
		}
		return singletonGson;
	}

	/**
	 * Creates a JSON String from an object
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJSON(Object obj) {
		Gson gson = getSingletonGson();
		return gson.toJson(obj);
	}

	/**
	 * Appends JSON converted object to a file
	 * 
	 * @param obj
	 * @param FileNameFromSrc
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static void appendToJSONFile(Object obj, String fileNameFromSrc)
			throws URISyntaxException, IOException {
		FileUtils.stringAppendToSmallFileContent(fileNameFromSrc, toJSON(obj));
	}

	/**
	 * Writes JSON converted object to a file
	 * 
	 * @param obj
	 * @param FileNameFromSrc
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public static void writeToJSONFile(Object obj, String fileNameFromSrcFolder)
			throws URISyntaxException, IOException {
		FileUtils.stringWriteToSmallFileContent(fileNameFromSrcFolder,
				toJSON(obj));
	}

	/**
	 * Gets an object from a JSON string
	 * 
	 * @param strJSON
	 * @param myClass
	 * @return
	 */
	public static <T> T fromJSON(String strJSON, Class<T> myClass) {
		Gson gson = getSingletonGson();
		return gson.fromJson(StringUtils.removeJavaComments(strJSON), myClass);
	}

	public static <T> T fromJSON(String strJSON, Type myType) {
		Gson gson = getSingletonGson();
		return gson.fromJson(StringUtils.removeJavaComments(strJSON), myType);
	}

	/**
	 * Gets an object from a file that stores JSON information
	 * 
	 * @param fileNameFromSrcFolder
	 * @param myClass
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */

	public static <T> T readFromJSONFile(String fileNameFromSrcFolder,
			Class<T> myClass) throws IOException, URISyntaxException {
		String s = FileUtils
				.readSmallFileContentToString(fileNameFromSrcFolder);
		return fromJSON(s, myClass);
	}

	public static <T> T readFromJSONFile(String fileNameFromSrcFolder,
			Type myType) throws IOException, URISyntaxException {
		String s = FileUtils
				.readSmallFileContentToString(fileNameFromSrcFolder);
		return fromJSON(s, myType);

	}

}
